#include <stdio.h>
#include <stdlib.h>
#include <netinet/ip.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define ARGS_CHECK(argc, num)                 \
    {                                         \
        if (argc != num)                      \
        {                                     \
            fprintf(stderr, "args error !n"); \
            return -1;                        \
        }                                     \
    }
#define ERROR_CHECK(ret, num, msg) \
    {                              \
        if (ret == num)            \
        {                          \
            perror(msg);           \
            exit(1);               \
        }                          \
    }
int main(int argc, char *argv[])
{
    ARGS_CHECK(3, argc);
    int fd_s = socket(PF_INET, SOCK_DGRAM, 0);
    ERROR_CHECK(-1, fd_s, "socket");
    //
    struct sockaddr_in saddr;
    saddr.sin_family = PF_INET;
    saddr.sin_port = htons(atoi(argv[2]));
    saddr.sin_addr.s_addr = inet_addr(argv[1]);
    bind(fd_s, (void *)&saddr, sizeof saddr);
    ERROR_CHECK(-1, fd_s, "bind");
    char buf[1024];
    socklen_t len = sizeof saddr;
    while (1)
    {
        fgets(buf,1024,stdin);
          if (-1 == sendto(fd_s, buf, 1024, 0, (void *)&saddr, len))
        {
            perror("sendto");
            continue;
        }
        if (-1 == recvfrom(fd_s, buf, 1024, 0, (void *)&saddr, &len))
        {
            perror("recvfrom");
            continue;
        }
      
        printf("recv from ip%s:port%d msg:%s\n", inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port), buf);
    }
    return 0;
}
